<template>
  <view class="profile-container">
    <van-nav-bar left-arrow :border="false" title="基本资料" @click-left="handleBack" />
    <view class="profile-wrapper">
      <view class="input-cell">
        <view class="prefix texts">头像</view>
        <view class="content" @click="state.isPhoto = true">
          <YAvatar :avatar="state.userinfo.Avatar" :SHState="state.userinfo.SHState"
            :status="state.userinfo.State == 0 ? '审核中' : ''" style="margin-left: 32rpx;" />
        </view>
        <view class="suffix arrow"></view>
      </view>
      <view class="input-cell">
        <view class="prefix texts">昵称</view>
        <view class="content texts">{{ state.userinfo.nickname }}</view>
        <view class="suffix arrow"
          @click="handleEdit(null, 'userinfo.nickname', state.userinfo.nickname, null, null, '修改昵称')"></view>
      </view>

      <view class="input-cell">
        <view class="prefix texts">性别</view>
        <view class="content texts">{{ state.userinfo.sex == 1 ? '男' : '女' }}</view>
        <!-- <view class="suffix arrow" @click="handleChooseSex"></view> -->
      </view>

      <view class="input-cell">
        <view class="prefix texts">出生日期</view>
        <view class="content texts">{{ state.userinfo.birthday.join('-') }}</view>
        <!-- <view class="suffix arrow" @click="proxy.$refs.datepickerRef.open()"></view> -->
      </view>

      <view class="input-cell">
        <view class="prefix texts">常驻城市</view>
        <view class="content texts">{{ state.userinfo.cityName[1] }}</view>
        <view class="suffix arrow" @click="proxy.$refs.citypickerRef.open()"></view>
      </view>

      <view class="input-cell">
        <view class="prefix texts">身高体重</view>
        <view class="content texts">{{ state.userinfo.hw.length ? state.userinfo.hw.join('cm·') + 'kg' : '' }}</view>
        <view class="suffix arrow" @click="proxy.$refs.hwpickerRef.open()"></view>
      </view>

      <view class="input-cell">
        <view class="prefix texts">职业</view>
        <view class="content texts">{{ state.userinfo.jobName[1] }}</view>
        <view class="suffix arrow" @click="proxy.$refs.jobpickerRef.open()"></view>
      </view>

      <view class="input-cell">
        <view class="prefix texts">个性签名</view>
        <view class="content texts">{{ state.userinfo.sign }}</view>
        <view class="suffix arrow"
          @click="handleEdit('textarea', 'userinfo.sign', state.userinfo.sign, '个性签名', '有趣的个性签名能让更多人认识你')"></view>
      </view>

      <view class="input-cell">
        <view class="prefix texts">微信号</view>
        <view class="content texts">{{ state.userinfo.wx }}</view>
        <view class="suffix arrow" @click="handleEdit(null, 'userinfo.wx', state.userinfo.wx, null, null, '修改微信号')">
        </view>
      </view>
    </view>

    <view class="tags-wrapper">
      <view class="tags-customize-navigator">
        <view class="title">个性标签</view>
        <view class="arrow" @click="tagsFn()"></view>
      </view>
      <YTags :tagGroup="state.tags" />
      <view class="modify-limit-tip">本月剩余{{ state.modifyLimit }}次修改次数</view>

      <van-button class="submit-long" :loading="state.isLoading" @click="handleSave">保存</van-button>

      <YPagedEdiotor :visible="state.editorObject.visible" :navTitle="state.editorObject.nav"
        :formKey="state.editorObject.key" :formValue="state.editorObject.value" :formTitle="state.editorObject.title"
        :formDescription="state.editorObject.description" :formType="state.editorObject.type"
        @onBack="state.editorObject.visible = false" @onSave="handleFormValueChange" />
    </view>

    <van-action-sheet v-model:show="state.sexOptions.visible" :actions="state.sexOptions.actions" cancel-text="取消"
      close-on-click-action @cancel="state.sexOptions.visible = false" />

    <uni-popup ref="citypickerRef" type="bottom">
      <van-picker title="选择城市" :columns="state.areaList"
        :columns-field-names="{ text: 'ShowName', value: 'ID', children: 'Children' }"
        @cancel="proxy.$refs.datepickerRef.close()" @confirm="handleConfirmCity" />
    </uni-popup>

    <uni-popup ref="hwpickerRef" type="bottom">
      <van-picker title="身高体重" :columns="state.hwList" @cancel="proxy.$refs.hwpickerRef.close()"
        @confirm="handleConfirmHw" />
    </uni-popup>

    <uni-popup ref="jobpickerRef" type="bottom">
      <van-picker title="职业" :columns="state.jobList"
        :columns-field-names="{ text: 'ShowName', value: 'ID', children: 'Children' }"
        @cancel="proxy.$refs.jobpickerRef.close()" @confirm="handleConfirmjob" />
    </uni-popup>
    <UploadHeadPhoto v-if="state.isPhoto" :isShow="state.isPhoto" @update:isShow="(ev) => state.isPhoto = ev"
      :curSex="state.userinfo.sex" :imgCount="1" @update:checkImg="ev => state.authImgList = ev" />
  </view>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted } from "vue"
import { onLoad } from '@dcloudio/uni-app'
import { areaList, jobList } from '@/assets/sim-data.js';

import YAvatar from '@/components/y-avatar/index.vue'
import YTags from '@/components/y-tags/index.vue'
import YPagedEdiotor from '@/components/y-paged-editor/index.vue'
import UploadHeadPhoto from '@/components/uploadHeadPhoto/index.vue'

import preferenceIcon from '@/assets/image/profile-preference.png';
import selfIcon from '@/assets/image/profile-self.png';
import favorsIcon from '@/assets/image/profile-favors.png';
import { getAuthorization, setAuthorization } from "@/utils/auth.js"

import {
  UserInfoUpdate, // 获取更新次数
  UserInfo, // 修改用户资料
} from "@/api/person/index.js"

import {
  getCity,
  getUserJob
} from "@/api/register/index.js"

// 修改用户信息 {"Value":[{"op":"replace","path":"ShowName","value":"帅哥1111"},{"op":"replace","path":"State","value":"0"}]}

//假数据
import { tags } from '@/assets/sim-data.js'

let { proxy } = getCurrentInstance()
const state = reactive({
  tags: {},
  isPhoto: false,
  authImgList: [],
  modifyLimit: 3,
  areaList: [],
  jobList: [],
  userinfo: {
    sex: 0,
    nickname: '',
    sign: '',
    wx: '',
    birthday: [],
    cityName: [],
    cityValue: [],
    hw: [],
    jobName: [],
    jobValue: []
  },

  editorObject: {
    type: 'input',
    nav: '', //导航标题
    key: '', //对应的字段名路径 例如 state.xxxx.xxxx， 但不需要state
    value: '', //表单值
    title: '', //标题
    description: '', //描述
    visible: false,//文本编辑器组件是否可见
  },

  sexOptions: {
    visible: false,
    actions: [
      { name: '男', callback: () => { state.userinfo.sex = 0 } },
      { name: '女', callback: () => { state.userinfo.sex = 1 } },
    ]
  },
  hwList: [],
  isLoading: false
})

onLoad((options) => {
  getCurrentUserInfo()
  UserInfoUpdateFn()
  UserInfoData()
})

// 获取用户最新数据
import { AuthStateStore } from "@/store/authIndex.js"
let AuthStore = AuthStateStore()
const UserInfoData = async () => {
  let data = await proxy.$get(UserInfo + getAuthorization('userId'))
  if (data.code == 200) {
    let userInfo = JSON.stringify(data.data)
    AuthStore.updateUserInfo(userInfo)
    getUserInfoData()
  }
}

// 获取用户信息
const getUserInfoData = () => {
  let userInfo = JSON.parse(getAuthorization("userInfo"))
  state.userinfo = {
    sex: userInfo.Sex,
    nickname: userInfo.ShowName,
    sign: userInfo.Intro,
    wx: userInfo.WX,
    birthday: userInfo.Birthday.split(' ')[0].split('-'),
    cityName: [userInfo.CityText, userInfo.CityText],
    cityValue: [],
    hw: [userInfo.Height, userInfo.Weight],
    jobName: ['', userInfo.StrJob],
    jobValue: [],
    State: userInfo.State,
    Avatar: userInfo.Avatar
  }
}


const datepickerRef = ref(null);
const citypickerRef = ref(null);
const hwpickerRef = ref(null);
const jobpickerRef = ref(null);

/**
 * @description 设置tag数据
 */
async function getCurrentUserInfo() {
  let tagData = tags;
  //转换接口数据为组件的数据格式
  tags.forEach((x, i) => {
    state.tags[x.CodeKey] = {
      name: x.ShowName,
      icon: i == 0 ? preferenceIcon : i == 1 ? selfIcon : favorsIcon,
      value: x.Tags,
      data: x,
    }
  })
  // let res = await getUserInfo(151879);
}

const handleSave = async () => {
  updateInfoFn()
}

const handleChooseSex = () => {
  state.sexOptions.visible = true;
}

const handleConfirmCity = (val) => {
  state.userinfo.cityValue = val.selectedValues;
  state.userinfo.cityName = val.selectedOptions.map(x => {
    if (x) { return x.ShowName }
  })
  state.userinfo.cityName = state.userinfo.cityName.filter(x => { return x !== null });
  proxy.$refs.citypickerRef.close();
}

const handleConfirmHw = (val) => {
  state.userinfo.hw = val.selectedValues;
  proxy.$refs.hwpickerRef.close();
}

const handleConfirmjob = (val) => {
  state.userinfo.jobValue = val.selectedValues;
  state.userinfo.jobName = val.selectedOptions.map(x => {
    if (x) { return x.ShowName }
  })
  state.userinfo.jobName = state.userinfo.jobName.filter(x => { return x !== null });
  proxy.$refs.jobpickerRef.close();
}

/**
 * @description 处理表单值变化
 * @param {Object} args -> { key: xxx.xxxx.xxx等完整的对象名路径 不要state, value: 编辑器的值 }
 */

let updateArr = ref(
  [
    { "op": "replace", "path": "State", "value": "0" }
  ]) // 更新人员数据
const handleFormValueChange = (args) => {
  console.log(args, 'args')
  let target = state;
  let keys = args.key.split('.');
  keys.forEach((key, i) => {
    if (i < keys.length - 1) {
      target = target[key];
    } else {
      addUpdateDn(key, args.value)
      target[key] = args.value;
    }
  })
  resetEditor();
}

// 添加修改信息
const addUpdateDn = (key, value, types = 1) => {
  if (state[key] != value && types == 1) {
    let itemName = ''
    if (key == 'nickname') itemName = 'ShowName'
    if (key == 'CityText') itemName = 'CityText'
    if (key == 'wx') itemName = 'WX'
    if (key == 'sign') itemName = 'Intro'
    let item = {
      "op": "replace",
      "path": itemName,
      "value": value
    }
    let isIndex = updateArr.value.findIndex(o => o.path == itemName)
    if (isIndex == -1) {
      updateArr.value.push(item)
    } else {
      updateArr.value[isIndex] = item
    }
  }
  if (types == 2) {
    let item = {
      "op": "replace",
      "path": key,
      "value": value
    }
    let isIndex = updateArr.value.findIndex(o => o.path == key)
    if (isIndex == -1) {
      updateArr.value.push(item)
    } else {
      updateArr.value[isIndex] = item
    }
  }
}

// 提交修改数据
const updateInfoFn = async () => {
  let userInfo = JSON.parse(getAuthorization("userInfo"))
  // 身高
  if (userInfo.Height != state.userinfo.hw[0]) {
    addUpdateDn('Height', state.userinfo.hw[0], 2)
  }
  // 体重
  if (userInfo.Weight != state.userinfo.hw[1]) {
    addUpdateDn('Weight', state.userinfo.hw[1], 2)
  }
  //职业
  if (userInfo.StrJob != state.userinfo.jobName[1]) {
    addUpdateDn('StrJob', state.userinfo.jobName[1], 2)
  }
  //城市
  if (userInfo.CityText.split('-')[1] != state.userinfo.cityName[1]) {
    addUpdateDn('CityText', state.userinfo.cityName[1], 2)
  }
  if (state.authImgList.length > 0) {
    updateArr.value.push({
      "op": "replace",
      "path": "Avatar",
      "value": state.authImgList[0].Path
    })
  }
  let params = {
    "Value": updateArr.value
  }
  state.isLoading = true
  try {
    let data = await proxy.$patch(UserInfo + getAuthorization("userId"), params)
    state.isLoading = false
    if (data.code == 200) {
      uni.showToast({
        title: "用户信息更新成功",
        icon: 'none'
      })
      uni.navigateTo({
        url: "/pages/home/index"
      })
      UserInfoData()
      UserInfoUpdateFn()
    }
  } catch (error) {
    state.isLoading = false
    uni.showToast({
      title: error.message,
      icon: "none"
    })
  }
}

const handleEdit = (type, key, value, title, description, nav) => {
  state.editorObject = {
    nav: nav,
    key: key,
    value: value,
    title: title,
    description: description,
    visible: true
  }
  if (type) {
    state.editorObject.type = type;
  }
}

function handleBack() {
  history.back();
}

function resetEditor() {
  state.editorObject = {
    type: 'input',
    nav: '',
    key: '',
    value: '',
    title: '',
    desription: '',
    visible: false
  }
}

const UserInfoUpdateFn = async () => {
  let data = await proxy.$get(UserInfoUpdate)
  if (data.code == 200) {
    state.modifyLimit = data.data
  }
}

const traversalFn = (dataList) => {
  dataList.forEach(o => {
    o.text = o.ShowName
    o.value = o.ID
    o.children = o.Children
    if (o.children.length) traversalFn(o.children)
  })
}
// 获取城市
const getCityFn = async () => {
  let data = await proxy.$get(getCity)
  if (data.code == 200) {
    state.areaList = data.data
  }
}



const getUserJobFn = async () => {
  let data = await proxy.$get(getUserJob)
  if (data.code == 200) {
    traversalFn(data.data)
    state.jobList = data.data
  }
}

const HeightWeightDataFn = () => {
  let childArr = []
  for (let i = 0; i < 120; i++) {
    if (i > 29) {
      childArr.push({
        text: i + 'kg',
        value: i
      })
    }
  }
  for (let i = 0; i < 230; i++) {
    if (i > 139) {
      state.hwList.push({
        text: i + 'cm',
        value: i,
        children: childArr
      })
    }
  }
}

const tagsFn = () => {
  uni.navigateTo({
    url: '/pages/home/person/labelPage/index'
  })
}

onMounted(() => {
  HeightWeightDataFn()
  getCityFn()
  getUserJobFn()
})



</script>

<style lang="scss" scoped>
.profile-container {
  position: fixed;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(247, 248, 249, 1);
}

.profile-wrapper {
  padding-top: 54rpx;
  background-color: rgba(255, 255, 255, 1);
}

.tags-wrapper {
  margin-top: 24rpx;
  background-color: rgba(255, 255, 255, 1);
  padding-top: 15rpx;
  padding-bottom: 30rpx;

  .tags-customize-navigator {
    height: 102rpx;
    padding: 0 34rpx;
    padding-left: 20rpx;
    display: flex;
    align-items: center;

    .title {
      line-height: 1;
      font-size: 30rpx;
      font-weight: 600;
      color: rgba(38, 38, 38, 1);
      flex: 1;
    }

    .arrow {
      background-image: url("@/assets/image/icon29.png");
      background-size: 85%;
      background-repeat: no-repeat;
      background-position: 50% 50%;
      height: 28rpx;
      width: 28rpx;
    }
  }

  //修改剩余次数
  .modify-limit-tip {
    margin-top: 36rpx;
    margin-bottom: 16rpx;
    text-align: center;
    color: rgba(102, 102, 102, 1);
    font-size: 24rpx;
    line-height: 1;
  }

  //保存按钮
  .submit-long {
    height: 100rpx;
    margin: 0 30rpx;
    background-color: rgba(38, 38, 38, 1);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 36rpx;
    color: rgba(255, 255, 255, 1);
    border-radius: 8rpx;
    width: calc(100% - 60rpx);
  }
}

.input-cell {
  padding-right: 30rpx;
}
</style>